package com.zw.yzk.kabu.data.repository;

import com.zw.yzk.kabu.data.network.task.Task;
import com.zw.yzk.kabu.data.constant.Constant;
import com.zw.yzk.kabu.data.network.ServiceGenerator;
import com.zw.yzk.kabu.data.network.entity.CollectedGoodsEntity;
import com.zw.yzk.kabu.data.network.service.GetCollectedGoodsService;
import com.zw.yzk.kabu.data.network.task.GetCollectedGoodsTask;

import javax.inject.Inject;

import rx.Observable;
import rx.functions.Func1;

/**
 * Created by zhanwei on 2017/1/12.
 */

public class CollectedGoodsListRepository extends CommonRepository {

    private int totalCount;

    @Inject
    public CollectedGoodsListRepository() {
        totalCount = GetCollectedGoodsTask.DEFAULT_GOODS_COUNT_PER_PAGE;
    }


    @Override
    protected Observable connectServer(Task task) {
        GetCollectedGoodsService service = ServiceGenerator.createService(GetCollectedGoodsService.class);
        GetCollectedGoodsTask goodsTask = (GetCollectedGoodsTask) task;

        if (goodsTask.start >= totalCount) {
            CollectedGoodsEntity entity = new CollectedGoodsEntity();
            //已经全部加载，直接返回空列表
            entity.errCode = Constant.RESULT_OK;
            entity.result.total = totalCount;

            return Observable.just(entity);
        } else {
            return service.getCollectedGoodsList(
                    goodsTask.start,
                    goodsTask.size,
                    goodsTask.userId,
                    goodsTask.accessToken);
        }
    }

    @Override
    protected Func1<CollectedGoodsEntity, Observable> getServerData() {
        return new Func1<CollectedGoodsEntity, Observable>() {
            @Override
            public Observable call(CollectedGoodsEntity entity) {
                totalCount = entity.result.total;
                return Observable.just(entity);
            }
        };
    }

}
